from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from rest_framework.response import Response
from rest_framework.views import APIView

from blog.my_decorators import access_log

# Create your views here.
'''一、视图函数的格式：
def 视图函数名(request,参数1,参数2,...):
    # 逻辑处理
    return HttpResponse("返回的内容")
二、视图函数的规则：
    1. 视图函数必须有一个参数，这个参数是一个HttpRequest对象，代表请求信息。
    2. 视图函数必须返回一个HttpResponse对象，代表响应信息。
    3. 视图函数的参数可以有多个，但是必须有一个参数是HttpRequest对象。
    4. 视图函数的参数可以有默认值。
    '''
@access_log
def blog_index(request):
    return HttpResponse("This is the index of the blog page.")

@access_log
def article_list(request):
    return HttpResponse("This is the list of articles.")
@access_log
def article_detail(request,article_id):
    return HttpResponse(f"This is the detail of article {article_id}.")
#年月正则匹配 archive/{year}/{month}
def archive(request,year,month):
    return HttpResponse(f"This is the archive for {year}/{month}.")

def show_child_views(request):
    return HttpResponse("<h2 style='color:red'>This is the show_child_views page.<h2>")

'''
5.2 请求对象（HttpRequest）与响应类型
    5.2.1 请求对象（HttpRequest）
        1. 请求对象（HttpRequest）是Django中用于封装HTTP请求的对象。
        2. 请求对象（HttpRequest）包含了请求的所有信  息，包括请求头、请求体、请求方法、请求路径、请求参数等。
'''
def show_request(request):
    #获取请求头
    headers = request.headers
    print("headers:",headers)
    print("request：",request)
    #获取请求体
    body = request.body
    print("body:",body)
    #获取请求方法
    method = request.method
    print("method:",method)
    #获取请求路径
    path = request.path
    print("path:",path)
    #获取请求参数(重要）
    query_params = request.GET
    print("GET对象：",request.GET)
    print("request.GET（name):",request.GET.get("name"))
    print("request.GET（age):",request.GET.get("age"))
    return HttpResponse("<h2 style='color:red'>This is the show_request page.<h2>")


#类视图的写法
class HomePageView(TemplateView):
    template_name = "home.html"

@access_log
def article_list2(request):
    #模板名称:article_list.html
    context={'title':"Python Django",'content':"This is a Django article.","address":{"prince":"广东省广州市天河区","city":"广州市","area":"天河区"}}
    return render(request,"article_list.html",context)

"""6.1 模板基础与变量渲染"""
def article_profile(request):
    return render(request,"article_profile.html",
                  {
        "title":"Python Django",
        "content":"This is a Django article."})


'''**6.2 模板标签与流程控制**'''
def article_list3(request):
    #创建文章列表数据
    articles = [
        {"title":"Python Django","content":"This is a Django article.","price":100,"publish_time":"2024-01-01"},
        {"title":"Python Flask","content":"This is a Flask article.","price":200,"publish_time":"2024-02-01"},
        {"title":"Python Tornado","content":"This is a Tornado article.","price":300,"publish_time":"2024-03-01"}
    ]
    return render(request,"blog/article_list3.html",{"articles":articles})


'''**6.3 模板继承与组件复用**'''
def template_re_use(request):
    return render(request,"blog/template_re_use.html")

'''6.4 静态文件管理与模板集成'''
def verify_static(request):
    return render(request,"static_cssjs_verify.html")

'''**6.5 文章列表展现综合练习**'''
def my_article_list(request):
    #创建文章列表数据
    """文章列表"""
    # 模文章列表数据，采用key:vlue表示，字段属性：title,author,price,content,pub_date,status
    articles = [
        {'id':1,'title': 'Python', 'author': '张三', 'price': 100, 'content': 'Python是一种高级编程语言', 'pub_date': '2023-05-01', 'status': 0},
        {'id':2,'title': 'Java', 'author': '李四', 'price': 200, 'content': 'Java是一种面向对象的编程语言', 'pub_date': '2023-05-02','status': 1},
        {'id':3,'title': 'C++', 'author': '王五', 'price': 300, 'content': 'C++是一种通用的编程语言', 'pub_date': '2023-05-03','status': 0},
        {'id':4,'title': 'JavaScript', 'author': '赵六', 'price': 400, 'content': 'JavaScript是一种脚本语言', 'pub_date': '2023-05-04','status': 1},
        {'id':5,'title': 'PHP', 'author': '钱七', 'price': 500, 'content': 'PHP是一种服务器端脚本语言', 'pub_date': '2023-05-05','status': 0},
        {'id':6,'title': 'Ruby', 'author': '孙八', 'price': 600, 'content': 'Ruby是一种动态编程语言', 'pub_date': '2023-05-06','status': 1},


    ]
    return render(request, 'blog/article.html', {'articles': articles})

"""**7.6 文章列表—模型综合练习**"""
from blog.sqlalchemy_model import *
def articles_from_db(request):
    #创建文章列表数据
    """文章列表"""
    # 模文章列表数据，采用key:vlue表示，字段属性：title,author,price,content,pub_date,status
    #查询数据库表中的所有数据（blog_article)
    articles = session.query(Article).all()
    #数据库session关闭
    session.close()
    return render(request, 'blog/article_from_db.html', {'articles': articles})

'''9.1 用户认证基础：登录、登出与权限控制'''
#用户登录
def user_login(request):

    if request.method == 'POST':
        # 调用Django内置的认证方法，验证用户登录信息
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            login(request, form.get_user())
            # 设置session
            request.session['user_id'] = '8002442424242'
            return redirect('/blog/home/')
    else:
        form = AuthenticationForm()
    return render(request, 'blog/login.html', {'form': form})

@login_required(login_url='/blog/user_login/')
def home(request):
    # 检查session是否存在
    user_id = request.session["user_id"]
    print("===========取出用户存入的会话信息：",user_id)

    return render(request, 'blog/home.html')

#用户退出
def user_logout(request):
    logout(request)
    # 清空整个 Session（包括数据库记录）
    request.session.flush()
    return redirect('/blog/user_login/')

'''9.4 自定义安全中间件：拦截未登录用户'''
def to_login(request):
    return render(request, 'login.html')

def get_session(request,key):
    try:
        value = request.session[key]
        return value
    except KeyError:
        # 如果没有找到 key，则返回 None 或其他默认值
        return None

def to_home(request):

    #取出用户信息
    user_info = get_session(request,"user_info")
    print("===========取出用户存入的会话信息：",user_info)
    return render(request, 'home.html')

def to_home2(request):

    #取出用户信息
    user_info = get_session(request,"user_info")
    print("===========取出用户存入的会话信息：",user_info)
    return render(request, 'home2.html')
def to_home3(request):
    #取出用户信息
    user_info = get_session(request,"user_info")
    print("===========取出用户存入的会话信息：",user_info)
    return render(request, 'home3.html')


class UserLogin(APIView):
    #使用post
    def post(self,request):
        # 获取表单数据
        print("request.data:", request.data)
        username = request.data.get("username")
        pwd = request.data.get("pwd")
        # 模拟的数据
        if username == "admin" and pwd == "123456":
            # 把登录用户编号存入session
            request.session["user_id"] = "999999"
            # 用户基本信息存入session
            request.session["user_info"] = {
                "username": "admin",
                "pwd": "123456",
                "id": "999999",
            }
            return Response({'code': 200, 'msg': '登录成功'})
        else:
            return Response({'code': 400,'msg': '登录失败'})


def to_ai_login(request):
    return render(request, 'sys/login.html')

def to_ai_menu(request):
    return render(request,'sys/menu.html')


def to_main_page(request):
    return render(request,'main.html')

def to_list_page(request):
    return render(request,'sys/list.html')

def to_operate_log(request):
    return render(request,'sys/operate_log_list.html')
def to_operate_log2(request):
    return render(request,'sys/operate_log_list2.html')



from common.db_util import *
from common.http_util import MyResult as Result

'''查询用户操作日志表'''
class UserOperateLog(APIView):
    # get请求
    def get(self,request):
        #sql查询语句
        page = None
        page_size = None
        dict1 = {}
        try:
            page = int(request.GET.get("page"))
            page_size = int(request.GET.get("page_size"))
            print("========page:",page,"page_size:",page_size)
            user_name=request.GET.get("user_name")
            if user_name is not None:
                dict1["user_name"] = user_name
                status=request.GET.get("status")
            status =request.GET.get("status")
            if status is not None:
                dict1["status"] = status
        except Exception as e:
            print("参数异常：",e)
        if page is None:
            page = 1
        if page_size is None:
            page_size = 10


        sql = "select * from sys_user_operate_log where 1=1 "
        if dict1 is not None and len(dict1) > 0:
            for key,value in dict1.items():
                if value is not None and value != "":
                    sql += " and "+key+" = :"+key
        # sql += " order by create_time desc"
        print("sql:",sql)
        log_dict = MySqlDb.query_by_page(sql,page=page,page_size=page_size,params=dict1)
        result = Result(code=0,msg="查询成功",result=log_dict).to_dict()
        return Response(result)


'''选择树'''
def to_select_tree(request):
    return render(request,'demo/select-tree-node.html')
